package cn.cnhis.online.activity.main.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.Button;
import android.widget.Toast;

import com.maning.updatelibrary.InstallUtils;
import com.smarx.notchlib.NotchScreenManager;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.cnhis.online.BuildConfig;
import cn.cnhis.online.R;
import cn.cnhis.online.activity.login.view.LoginActivity;
import cn.cnhis.online.activity.main.contract.IMainContract;
import cn.cnhis.online.activity.main.presenter.MainPresenter;
import cn.cnhis.online.base.ActivityStack;
import cn.cnhis.online.base.BaseMvpActivity;
import cn.cnhis.online.customerView.AppUpdateDialog;
import cn.cnhis.online.customerView.NotificationHelper;
import cn.cnhis.online.mymodule.Api;
import cn.cnhis.online.mymodule.Constants;
import cn.cnhis.online.mymodule.Utils.AndroidBugWorkaround;
import cn.cnhis.online.mymodule.Utils.EquipmentInfoCollection;
import cn.cnhis.online.mymodule.Utils.EquipmentPO;
import cn.cnhis.online.mymodule.Utils.PackageUtil;
import cn.cnhis.online.mymodule.Utils.PhotoUtils;
import cn.cnhis.online.mymodule.Utils.StatusBarUtils;
import cn.cnhis.online.mymodule.sp.MySpUtils;
import cn.cnhis.online.service.MqttService;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @author 刘祥龙
 * @describe
 * @date 2020/2/28  15:38
 * - generate by MvpAutoCodePlus plugin.
 */

public class MainActivity extends BaseMvpActivity<IMainContract.View, IMainContract.Presenter> implements IMainContract.View, AppUpdateDialog.OnUpdateDialogListener {

    @BindView(R.id.webview)
    WebView webView;
    @BindView(R.id.btn_load)
    Button btnLoad;
    private String downLoadUrl;
    private String router = "";
    private EquipmentPO equipmentInfo;
    private AppUpdateDialog appUpdateDialog;
    private MessageReciver messageReciver;
    private String sysLoginSessionId;

//    public static final String TEST_URL_web = "http://cnhis.f3322.org:10080/dev_crmweb/h5/#/home";
//    public static final String TEST_URL_web = "http://192.168.1.3:8080";

    private String webMessage;

    /*扫描请求code*/
    private int REQUEST_CODE_SCAN = 999;
    /*获取照片*/
    private int REQUEST_FILE = 888;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NotchScreenManager.getInstance().setDisplayInNotch(this);

        ActivityStack.getInstance().pushActivity(this);
        setContentView(R.layout.activity_main);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onContentChanged() {
        super.onContentChanged();
        initWebview();
        initReciver();
        getPresenter().getAppVersion("" + PackageUtil.getVersionCode(this));
        getPresenter().getMenuShowColor();
        EquipmentInfoCollection equipmentInfoCollection = new EquipmentInfoCollection();
        equipmentInfo = equipmentInfoCollection.getEquipmentInfo(this);


    }

    private void initReciver() {
        messageReciver = new MessageReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.MESSAGE);
        registerReceiver(messageReciver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (appUpdateDialog != null) {
            appUpdateDialog.dismiss();
            appUpdateDialog = null;
        }
        MqttService.actionStop(this);
        if (messageReciver != null) {
            unregisterReceiver(messageReciver);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        webMessage = intent.getStringExtra(Constants.MESSAGE_KEY);
        if (webMessage != null) {
            webView.loadUrl("javascript:getAppMessage(" + webMessage + ")");
            webMessage = null;
            NotificationHelper.getInstance(getApplicationContext()).getNotificationManager().cancel(1);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMqttConnectReceiver != null) {
            unregisterReceiver(mMqttConnectReceiver);
        }
        if (mMqttMsgReceiver != null) {
            unregisterReceiver(mMqttMsgReceiver);
        }

        if (BuildConfig.DEBUG) Log.d("MainActivity", "onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerMqttConnectReceiver();
        startMqttService();
        registerMqttMsgReceiver();

        if (BuildConfig.DEBUG) Log.d("MainActivity", "onResume");


    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (BuildConfig.DEBUG) Log.d("MainActivity", "onRestart");
    }


    private void initWebview() {
        sysLoginSessionId = MySpUtils.getSysLoginSessionId(this);
        Map<String, String> map = new HashMap<>();
        map.put("sysLoginSessionId", sysLoginSessionId);



        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setDatabaseEnabled(true);
//        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setAppCacheEnabled(true);
//        webView.getSettings().setCacheMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.addJavascriptInterface(new JavaScriptinterface(this),
                "Android");
        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (BuildConfig.DEBUG) Log.d("MainActivity", "页面加载完成1");
                if (webMessage != null) {
//                    view.loadUrl("javascript:getAppMessage(" + webMessage + ")");
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                if (BuildConfig.DEBUG) Log.d("MainActivity", "url == ==>" + url);
                view.loadUrl(url);
                return true;
            }


        });

        webView.setWebChromeClient(new WebChromeClient() {
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
//                Log.d("MainActivity", message);
                if (message != null) {
                    if (message.startsWith("Android")) {
                        String[] arr = message.split(":");
                        router = arr[1];
                    }
                }


            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    //加载完成

//                    if (BuildConfig.DEBUG) Log.d("MainActivity", "页面加载完成2");
//                    if (BuildConfig.DEBUG) Log.d("MainActivity", "onProgressChanged=" + webMessage);
//                    if (BuildConfig.DEBUG) Log.d("MainActivity", "router1111=" + router);
//                    if (webMessage != null)
//                        if (!"/serverChat".equals(router) && !"/OnlineChat".equals(router) && !"/message/announce".equals(router) && !"/message/notice".equals(router)) {
//                            if (BuildConfig.DEBUG) Log.d("MainActivity", "1111");
//                            view.loadUrl("javascript:getAppMessage(" + webMessage + ")");
//                        }
                }


            }
        });


//        webView.loadUrl(URL_web);
        if (BuildConfig.DEBUG) Log.d("MainActivity", sysLoginSessionId);
        if (BuildConfig.DEBUG)
            Log.d("MainActivity", Api.TEST_URL_web + "?sysLoginSessionId=" + sysLoginSessionId);

        setWebViewMargin(webView);
        AndroidBugWorkaround.assistActivity(this);

        webMessage = getIntent().getStringExtra(Constants.MESSAGE_KEY);
        if (BuildConfig.DEBUG) Log.d("MainActivity", "webMessage==" + webMessage);
        webView.loadUrl(Api.TEST_URL_web + "?sysLoginSessionId=" + sysLoginSessionId);


    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ("/home".equals(router)) {
                Log.d("MainActivity", "onConsoleMessage: 主页");
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    //弹出提示，可以有多种方式
                    Toast.makeText(this, "再次点击退出程序", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    finish();
                }
            }
//            else if ("/serverChat".equals(router) || "/OnlineChat".equals(router) || "/message/announce".equals(router) || "/message/notice".equals(router)) {
//                webView.loadUrl(Api.TEST_URL_web + "?sysLoginSessionId=" + sysLoginSessionId);
//            }
            else {
                if (webView.canGoBack())
                    webView.goBack();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }


    /*  安卓 调用  jS  示例*/
    public void testAndroidLoadJs() {
        /*javacalljs   必须挂载到 window 上面 不然无法调用 */
        webView.loadUrl("javascript:javacalljs(此处只能传递字符串类型数据)");
    }

    @Override
    public void getAppVersion(Map map) {

        JSONObject jsonObject = toJSONObject(map);
        try {
            if (jsonObject.getString(Constants.RESULT).equals(Constants.SUCCESS)) {
                if ("1".equals(jsonObject.getJSONObject(Constants.MAP).getString("isUpdate"))) {
                    downLoadUrl = jsonObject.getJSONObject(Constants.MAP).getString("url");
                    appUpdateDialog = new AppUpdateDialog(this, jsonObject.getJSONObject(Constants.MAP));
                    appUpdateDialog.setOnUpdateDialogListener(this);
                    appUpdateDialog.show();
                }
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.Failure)) {
                Toast.makeText(this, "获取版本信息失败！", Toast.LENGTH_SHORT).show();
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.NO_LOGIN)) {
                Toast.makeText(this, "免密校验失败！", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onNo() {
        if (appUpdateDialog != null && appUpdateDialog.isShowing()) {
            appUpdateDialog.dismiss();
        }
//        ToolUitls.openDirChooseFile(MainActivity.this, REQUEST_FILE, null, "image/*");

    }

    @Override
    public void onYes() {
        if (appUpdateDialog != null && appUpdateDialog.isShowing()) {
            appUpdateDialog.dismiss();
        }

        Toast.makeText(this, "下载中，下载完成将会自动安装！", Toast.LENGTH_SHORT).show();


        //下载APK
        InstallUtils.with(MainActivity.this)
                //必须-下载地址
                .setApkUrl(downLoadUrl)
                //非必须-下载保存的文件的完整路径+/name.apk，使用自定义路径需要获取读写权限
                .setApkPath(Environment.getExternalStorageDirectory() + File.separator + "online.apk")
                //非必须-下载回调
                .setCallBack(new InstallUtils.DownloadCallBack() {
                    @Override
                    public void onStart() {
                        //下载开始

                        if (BuildConfig.DEBUG) Log.d("MainActivity", "下载开始");
                    }

                    @Override
                    public void onComplete(String path) {
                        if (BuildConfig.DEBUG) Log.d("MainActivity", path);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            //先获取是否有安装未知来源应用的权限
                            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
                            if (!haveInstallPermission) {
                                //跳转设置开启允许安装
                                Uri packageURI = Uri.parse("package:" + MainActivity.this.getPackageName());
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                startActivityForResult(intent, 1000);
//                                                return;
                            }
                        }

                        //下载完成
                        //先判断有没有安装权限---适配8.0
                        //如果不想用封装好的，可以自己去实现8.0适配
                        InstallUtils.checkInstallPermission(MainActivity.this, new InstallUtils.InstallPermissionCallBack() {
                            @Override
                            public void onGranted() {
                                //去安装APK
//                                                installApk(...);
                                InstallUtils.installAPK(MainActivity.this, path, new InstallUtils.InstallCallBack() {
                                    @Override
                                    public void onSuccess() {
                                        //onSuccess：表示系统的安装界面被打开
                                        //防止用户取消安装，在这里可以关闭当前应用，以免出现安装被取消
                                        Toast.makeText(MainActivity.this, "正在安装程序", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onFail(Exception e) {
                                        if (BuildConfig.DEBUG)
                                            Log.d("MainActivity", "e:" + e);
                                        //安装出现异常，这里可以提示用用去用浏览器下载安装
                                    }
                                });
                            }

                            @Override
                            public void onDenied() {

                            }
                        });

                    }

                    @Override
                    public void onLoading(long total, long current) {
                        //下载中
                        if (BuildConfig.DEBUG) Log.d("MainActivity", "下载中");
                    }

                    @Override
                    public void onFail(Exception e) {
                        //下载失败
                        if (BuildConfig.DEBUG) Log.d("MainActivity", "下载失败");
                    }

                    @Override
                    public void cancle() {
                        //下载取消
                        if (BuildConfig.DEBUG) Log.d("MainActivity", "下载取消");
                    }
                })
                //开始下载
                .startDownload();

    }


    @Override
    public void getMenuShowColor(Map map) {
        JSONObject jsonObject = toJSONObject(map);
        try {
            if (jsonObject.getString(Constants.RESULT).equals(Constants.SUCCESS)) {
                String color = jsonObject.getJSONObject(Constants.OBJECT).getString("value");
                if (BuildConfig.DEBUG) Log.d("MainActivity", "color==" + color);
                MySpUtils.setThemeColor(this, color);
                String themeColor = MySpUtils.getThemeColor(this);
                if (BuildConfig.DEBUG) Log.d("MainActivity", "themeColor==" + themeColor);
                StatusBarUtils.setStatusBar(this, true, false, color);
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.Failure)) {
                Toast.makeText(this, "获取主题颜色失败！", Toast.LENGTH_SHORT).show();
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.NO_LOGIN)) {
                Toast.makeText(this, "免密校验失败！", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void loadFile(Map map) {
        if (BuildConfig.DEBUG) Log.d("MainActivity", "map:" + map);
        JSONObject jsonObject = toJSONObject(map);
        try {
            if (jsonObject.getString(Constants.RESULT).equals(Constants.SUCCESS)) {
                JSONObject obj = jsonObject.getJSONObject(Constants.MAP);
                obj.put("type",type);
                String url = obj.toString();
                if (BuildConfig.DEBUG)
                    Log.d("MainActivity", "javascript:imageCallBack(" + url + ")");
                webView.loadUrl("javascript:imageCallBack(" + url + ")");
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.Failure)) {
                Toast.makeText(this, "上传图片失败！", Toast.LENGTH_SHORT).show();
            } else if (jsonObject.getString(Constants.RESULT).equals(Constants.NO_LOGIN)) {
//                Toast.makeText(this, "免密校验失败！", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /*上传文件类型*/
    private String type;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("MainActivity", "webView.canGoBack(): " + webView.canGoBack());
            String router = (String) msg.obj;
            Log.d("MainActivity", "handleMessage: router--->" + router);
            webView.loadUrl(Api.TEST_URL_web + "?sysLoginSessionId=" + sysLoginSessionId);
        }
    };


    public class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的   js 调用 android    window.Android.loginOut()
         */
        @JavascriptInterface
        public void loginOut() {
            finish();
        }






        @JavascriptInterface
        public void backToAfter(String router) {
            Log.d("MainActivity", "backToAfter: " + "被调用");
            Log.d("MainActivity", "router: " + router);
            Message message = handler.obtainMessage();
            message.obj = router;
            handler.sendMessage(message);
        }


        @JavascriptInterface
        public void backToLogin() {
            MySpUtils.clear(MainActivity.this);
            startOterActivity(MainActivity.this, LoginActivity.class);
            finish();
        }

        @JavascriptInterface
        public void callPhone(String phone) {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + phone));
            startActivity(intent);
        }


        @JavascriptInterface
        public void loadFile(String type) {
            MainActivity.this.type = type;
            /**/
//            ToolUitls.openDirChooseFile(MainActivity.this, REQUEST_FILE, null, "file/*");
            PhotoUtils.pickImage(MainActivity.this, REQUEST_FILE);

        }


        @JavascriptInterface
        public void goBack() {
            finish();
        }

        @JavascriptInterface
        public void openCamera() {
            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
            ZxingConfig config = new ZxingConfig();
            config.setPlayBeep(true);//是否播放扫描声音 默认为true
            config.setShake(true);//是否震动  默认为true
            config.setDecodeBarCode(true);//是否扫描条形码 默认为true
            config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色
            config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色
            config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色
            config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
            intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
            startActivityForResult(intent, REQUEST_CODE_SCAN);
        }

        /* 手机各种信息 */
        @JavascriptInterface
        public String getMobileInfo() {
            int versionCode = PackageUtil.getVersionCode(MainActivity.this);
            equipmentInfo.setVersionCode("" + versionCode);
            String s = getGson().toJson(equipmentInfo).toString();
            return s;
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                if (BuildConfig.DEBUG) Log.d("MainActivity", content);
                webView.loadUrl("javascript:cameraCallBack(" + content + ")");
            }
        } else if (requestCode == REQUEST_FILE && resultCode == RESULT_OK) {
//            Uri uri = data.getData();
//            if (BuildConfig.DEBUG) Log.d("MainActivity", "uri:" + uri);
//            String path = uri.getPath();
//            if (BuildConfig.DEBUG) Log.d("MainActivity", "path====>" + path);

            String path = PhotoUtils.getPathFromUri(data, this);
            File file = new File(path);
            if (BuildConfig.DEBUG)
                Log.d("MainActivity", "file.getAbsolutePath-====>" + file.getAbsolutePath());

            Luban.with(this)
                    .load(file)                                   // 传人要压缩的图片列表
                    .ignoreBy(100)                                  // 忽略不压缩图片的大小
                    .setTargetDir(Environment.getExternalStorageDirectory().getAbsolutePath())                        // 设置压缩后文件存储位置
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
//                            Toast.makeText(MainActivity.this, "文件压缩中", Toast.LENGTH_SHORT).show();

                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
//                            Toast.makeText(MainActivity.this, "文件发送中", Toast.LENGTH_SHORT).show();
                            getPresenter().loadFile(file);

                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                            e.printStackTrace();
                        }
                    }).launch();    //启动压缩
        }
    }

    @Override
    public void showErr(String e) {
        Toast.makeText(this, e, Toast.LENGTH_SHORT).show();
    }

    @Override
    public IMainContract.Presenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    public IMainContract.View createView() {
        return this;
    }


    /**
     * 注册 连接
     */
    private void registerMqttConnectReceiver() {
        initmMqttConnectReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MqttService.INTENT_FILTER_CONNECT);
        registerReceiver(mMqttConnectReceiver, filter);
    }


    /**
     * 初始化 mqtt 广播接收器 连接
     */
    private BroadcastReceiver mMqttConnectReceiver;
    private int retryConnectCount;
    private boolean notStarAndRegister = true;

    private void initmMqttConnectReceiver() {
        if (mMqttConnectReceiver == null) {
            mMqttConnectReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if (intent.getBooleanExtra(MqttService.ARG_MQTT_CONNECT, false)) {
//                        Toast.makeText(MainActivity.this, "连接成功！", Toast.LENGTH_SHORT).show();
                        retryConnectCount = 0;
                        if (notStarAndRegister) {
                            startMqttService();
                            registerMqttMsgReceiver();
                        }
                    } else {
                        if (retryConnectCount < 7) {
                            ++retryConnectCount;
//                            Toast.makeText(MainActivity.this, "连接失败, 尝试重连...", Toast.LENGTH_SHORT).show();
//                            LogUtils.LOGE(TAG, "MainActivity:onReceive: 连接失败, 第" + retryConnectCount + "尝试重连...");
                            notStarAndRegister = true;
                            onResume();
                        } else {
//                            Toast.makeText(MainActivity.this, "连接失败,尝试多次仍失败,请检查配置...", Toast.LENGTH_SHORT).show();
                            MqttService.actionStop(MainActivity.this);
                        }
                    }
                }
            };
        }
    }

    /**
     * 初始化 mqtt 广播接收器  消息
     */
    private BroadcastReceiver mMqttMsgReceiver;

    private void initmMqttMsgReceiver() {
        if (mMqttMsgReceiver == null) {
            mMqttMsgReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    notStarAndRegister = false;
                    String message = intent.getStringExtra(MqttService.ARG_MQTT_MESSAGE);
                    handleMessage(message);//处理消息
                }
            };
        }
    }

    /**
     * 注册消息  广播 接收
     */
    private void registerMqttMsgReceiver() {
        initmMqttMsgReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(MqttService.INTENT_FILTER_MQTT);
        registerReceiver(mMqttMsgReceiver, filter);
    }

    /**
     * 启动mqtt service
     */
    private void startMqttService() {
        notStarAndRegister = false;
        String mqinfo = MySpUtils.getMQINFO(this);
        if (BuildConfig.DEBUG) Log.d("MainActivity", "mqinfo=" + mqinfo);
        try {
            JSONObject jsonObject = new JSONObject(mqinfo);
            if (BuildConfig.DEBUG) Log.d("MainActivity", jsonObject.toString());
            MqttService.actionStart(this,
                    jsonObject.getString(Constants.MQ_SERVER_IP),
                    jsonObject.getString(Constants.MQ_SERVER_PORT),
                    jsonObject.getString(Constants.MQ_SERVER_TOPIC));
//            MqttService.actionStart(this,
//                    "47.106.176.156",
//                    "1883",
//                    "100"
//            );
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 处理消息
     *
     * @param message
     */
    private void handleMessage(String message) {
        // 云his 消息发送 经过转码 此处需要转码
        if (BuildConfig.DEBUG) Log.d("MainActivity", "mMessage=>" + message);
//        webView.loadUrl("javascript:getAppMessage(" + mMessage + ")");
//        NotificationHelper.getInstance(getApplicationContext()).show(this, message);
    }


    private class MessageReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

//            if (intent.getAction().equals(Intent.ACTION_MAIN)) {
            String message = intent.getStringExtra(Constants.MESSAGE_KEY);
//            if (BuildConfig.DEBUG) Log.d("MessageReciver", "mMessage=>" + message);
//            webView.loadUrl("javascript:getAppMessage(" + message + ")");
            NotificationHelper.getInstance(getApplicationContext()).getNotificationManager().cancel(1);
//            }

        }
    }


}

